package DeadLock;

import java.util.Date;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class DeadLockDemo1 {
    public static final Semaphore a1 = new Semaphore(1);
    public static final Semaphore a2 = new Semaphore(1);

    public static void main(String[] args) {
     new Thread(){
         @Override
         public void run() {
             try {
                 System.out.println(new Date() + "线程A: 开始执行");
                 //获取资源1的许可
                 if (DeadLockDemo1.a1.tryAcquire(1, TimeUnit.SECONDS)){

                     System.out.println(new Date() + "Lock锁 锁住了 资源a");
                     //获取资源2的许可
                     if (DeadLockDemo1.a2.tryAcquire(1,TimeUnit.SECONDS)){
                         System.out.println(new Date() + "Lock锁 锁住了 资源b");
                         Thread.sleep(3000);
                     }
                 }else {
                     System.out.println(new Date() + "Lock锁 锁 资源b 失败");
                 }
                 //释放许可
                 DeadLockDemo1.a1.release();
                 DeadLockDemo1.a2.release();
             } catch (InterruptedException e) {
                 throw new RuntimeException(e);
             }
         }
     }.start();

        System.out.println("----------------------------------------");
        new Thread(){
            @Override
            public void run() {
                try {
                    System.out.println(new Date() + "线程B: 开始执行");
                    if (DeadLockDemo1.a2.tryAcquire(1,TimeUnit.SECONDS)){
                        System.out.println(new Date() + "Lock锁 锁住了 资源B");
                        if (DeadLockDemo1.a1.tryAcquire(1,TimeUnit.SECONDS)){
                            System.out.println(new Date() + "Lock锁 锁住了 资源A");
                        }
                    }else {
                        System.out.println(new Date() + "Lock锁 锁 资源b 失败");
                    }
                    //释放许可
                    DeadLockDemo1.a1.release();
                    DeadLockDemo1.a2.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();


     }
}

